//
//  ConsolidatedPaymentPayController.m
//  NtoccShipper
//
//  Created by 张天兴 on 2024/5/13.
//  Copyright © 2024 zhuchongjin. All rights reserved.
//

#import "ConsolidatedPaymentPayController.h"
#import "ConsolidatePayDataCell.h"
#import "ConsolidatePayPersenCell.h"
#import "ConsolidatePayPhoneSelectedCell.h"
#import "ConsolidatePayCodeCell.h"
#import "StaffCodingTextFieldCell.h"
#import "NYSExcDescView.h"
@interface ConsolidatedPaymentPayController ()<UITableViewDelegate,UITableViewDataSource>{
    NSArray *titleArr;
    int timeOld;
    NSTimer * _timer;
    NSString *currentPaymentAmount;
    NSString *payeeType;
}
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic, strong) CJButton *contentButton;
@property (nonatomic, strong) NSMutableArray *priceArr;
@property (nonatomic, strong) NSMutableArray *phoneArr;
@property (nonatomic, strong) UIButton *driceButton;
@property (nonatomic, strong) UIButton *daiShouRButton;
@property (nonatomic, strong) UITextField *phoneTextField;
@property (nonatomic, strong) UITextField *codeTextField;
@property (nonatomic, strong) UIButton *codeButton;
@property (nonatomic, strong) NSString *needSmsCode;
@property (nonatomic, strong) NSString *phoneStr;
@property (nonatomic, strong) NSDictionary *dicData;
@property (nonatomic, strong) UILabel *cententLabel;
@property (nonatomic, strong) NSString *payType;
@property (nonatomic, strong) NYSExcDescView *exDescView;
@end

@implementation ConsolidatedPaymentPayController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleName:CJLString(@"确认打款")];
    [self setBackLeftButton:@""];
    self.phoneStr = @"";
    self.payType = @"";
    payeeType = @"1";
    self.priceArr = [@[] mutableCopy];
    self.phoneArr = [@[] mutableCopy];
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
    }];
    [self.tableView registerNib:[UINib nibWithNibName:@"ConsolidatePayDataCell" bundle:nil] forCellReuseIdentifier:@"ConsolidatePayDataCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"StaffCodingTextFieldCell" bundle:nil] forCellReuseIdentifier:@"StaffCodingTextFieldCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ConsolidatePayPersenCell" bundle:nil] forCellReuseIdentifier:@"ConsolidatePayPersenCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ConsolidatePayPhoneSelectedCell" bundle:nil] forCellReuseIdentifier:@"ConsolidatePayPhoneSelectedCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ConsolidatePayCodeCell" bundle:nil] forCellReuseIdentifier:@"ConsolidatePayCodeCell"];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.contentButton];
    titleArr = @[@"货主应付总金额",@"司机实收现金总金额",@"分配油费总金额",@"预付总金额",@"此次付款金额"];
    [self loadData];
}
- (void)loadData {
    [self.priceArr removeAllObjects];
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail/getOrderDetailBatchPayment",CJBaseUrl);
    NSDictionary *dicPar = @{
        @"orderDetailCodes":self.orderDetailCodes,

    };
    
    WS(ws);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
        ws.dicData = responseObject;
        [ws.priceArr addObject:responseObject[@"allSumAmount"]];
        [ws.priceArr addObject:responseObject[@"driverAmount"]];
        [ws.priceArr addObject:responseObject[@"oilTotalAmount"]];
        [ws.priceArr addObject:responseObject[@"advancePaymentAmount"]];
        [ws.priceArr addObject:responseObject[@"currentPaymentAmount"]];
        currentPaymentAmount = responseObject[@"currentPaymentAmount"];
        if ([CJStringWithFormat(@"%@",responseObject[@"needSmsCode"]) isEqualToString:@"yes"]) {
            [self postPhoneListNetWorking];
        }
        [ws.tableView reloadData];
        } failure:^(NSError * _Nonnull error) {
            
        }];
   
}
//请求手机号列表
- (void)postPhoneListNetWorking{
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/arpaTransfer/getConfigPhoneBycx",CJBaseUrl);
    NSDictionary *dicPar = @{};
    WS(ws);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
        ws.phoneArr = responseObject;
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return titleArr.count;
    }
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([CJStringWithFormat(@"%@",self.dicData[@"needSmsCode"]) isEqualToString:@"yes"]) {
        return 5;
    }else{
        return 3;
    }
   
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        ConsolidatePayDataCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConsolidatePayDataCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text = titleArr[indexPath.row];
        cell.pricesLabel.text = CJStringWithFormat(@"%@",self.priceArr[indexPath.row]);
        return cell;
    }else if(indexPath.section == 1){
        StaffCodingTextFieldCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"StaffCodingTextFieldCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text = @"打款商户";
        self.cententLabel = cell.cententLabel;
        return cell;
    }else if(indexPath.section == 2){
        ConsolidatePayPersenCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConsolidatePayPersenCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.driceButton = cell.driceButton;
        self.daiShouRButton = cell.daishourenButton;
        [self.driceButton setImage:[UIImage imageNamed:@"zcj_selectedCir"] forState:(UIControlStateNormal)];
        [self.daiShouRButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
        [self.driceButton addTarget:self action:@selector(driceButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
        [self.daiShouRButton addTarget:self action:@selector(daiShouRButtonAction) forControlEvents:(UIControlEventTouchUpInside)];

        return cell;
    }else if(indexPath.section == 3){
        ConsolidatePayPhoneSelectedCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConsolidatePayPhoneSelectedCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.phoneTextField = cell.phoneTextField;
        self.phoneTextField.text = self.phoneStr;
        self.phoneTextField.userInteractionEnabled = NO;
        return cell;
    }else{
        ConsolidatePayCodeCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConsolidatePayCodeCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.codeButton = cell.codeButton;
        [self.codeButton addTarget:self action:@selector(btnGetAouthCodeAction:) forControlEvents:(UIControlEventTouchUpInside)];
        self.codeTextField = cell.codeTextField;
        self.codeTextField.keyboardType = UIKeyboardTypeDecimalPad;
        self.codeButton.userInteractionEnabled = YES;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 44;
    }
    return  60;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"请选择" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        for (int i = 0; i < self.phoneArr.count ; i++) {
            UIAlertAction *updateAct = [UIAlertAction actionWithTitle: CJStringWithFormat(@"%@",self.phoneArr[i]) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                self.phoneStr = CJStringWithFormat(@"%@",self.phoneArr[i]);
                [self.tableView reloadSection:3 withRowAnimation:(UITableViewRowAnimationNone)];
            }];
            [alertC addAction:updateAct];
        }

        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertC animated:YES completion:^{
            
        }];
    }else if (indexPath.section == 1){
        WS(ws);
        ws.exDescView.isHightType = @"1";
        ws.exDescView.block = ^(NSString *code, NSString *merchantCode, NSString *accountType) {
            if ([accountType intValue] == 0) {
                self.cententLabel.text = @"浦发支付账户";
                self.payType = @"1";
            }else if ([accountType intValue] == 1){
                self.cententLabel.text = @"快钱支付账户";
                self.payType = @"2";
            }else if ([accountType intValue] == 2){
                self.cententLabel.text = @"光大支付账户";
                self.payType = @"3";
            }
            [ws.exDescView removeFromSuperview];
        };
        ws.exDescView.returnBlock = ^(NSString *typeStr) {
            [ws.exDescView removeFromSuperview];
        };
        [[UIApplication sharedApplication].keyWindow addSubview:ws.exDescView];
    }
}
- (NYSExcDescView *)exDescView {
    if (!_exDescView) {
        CGFloat width = SCREEN_WIDTH;
        CGFloat height = SCREEN_HEIGHT*0.5 + 60 + 15  + 180 + 80;
        _exDescView = [[NYSExcDescView alloc] initWithFrame:CGRectMake(0, 100, width, height) upcode:@"" Isremit:@"1"];
    }
    return _exDescView;
}
- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, CJTableToTopHeight + kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - kNavBarHeight -CJTableToTopHeight - 30),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(NO)
        ;
    }
    return _tableView;
}
- (CJButton *)contentButton{
    if (!_contentButton) {
        _contentButton = CJButton.btnInit
        .btnFrame(CGRectMake(50,CGRectGetMaxY(self.tableView.frame) + 10,SCREEN_WIDTH - 100,50))
        .btnText(@"确认打款")
        .btnNormalTitleColor([UIColor cjWhiteColor])
        .btnBgColor([UIColor cjMainColor])
        .btnTargetAction(self, @selector(btnCancleAction:))
        .btnCornerRadius(10)
        .btnCornerWidth(1)
        .btnCornerColor([UIColor cjMainColor])
        ;
    }
    return _contentButton;
}
- (void)driceButtonAction{
    [self.driceButton setImage:[UIImage imageNamed:@"zcj_selectedCir"] forState:(UIControlStateNormal)];
    [self.daiShouRButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
    payeeType = @"1";
}
- (void)daiShouRButtonAction{
    [self.driceButton setImage:[UIImage imageNamed:@"zcj_unSelectedCir"] forState:(UIControlStateNormal)];
    [self.daiShouRButton setImage:[UIImage imageNamed:@"zcj_selectedCir"] forState:(UIControlStateNormal)];
    payeeType = @"2";
}
- (void)btnGetAouthCodeAction:(CJButton *)sender{
    
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/arpaTransfer/sendVerificationCodeBycx",CJBaseUrl);
    NSDictionary *dicPar = @{
        @"amount":currentPaymentAmount,
        @"phone": self.phoneStr
    };
    
    @weakify(self);
    [[HDNetworking sharedHDNetworking] POST:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        @strongify(self);
//        DLog(@"++++++++%@",responseObject);
        NSString *status = CJStringWithFormat(@"%@",responseObject[@"status"]);
            self.codeButton.userInteractionEnabled = NO;
            timeOld = 60;
            [self startTimer];
        } failure:^(NSError * _Nonnull error) {
            
        }];

}
- (void)startTimer{
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireOdlM) userInfo:nil repeats:YES];
}
- (void)timerFireOdlM{
    
    NSString * str =[NSString stringWithFormat:@"(%ds)",timeOld];
//    [self.btnGetCode setTitle:str forState:UIControlStateNormal];
    [self.codeButton setTitle:str forState:UIControlStateNormal];
    timeOld--;
    if (timeOld==0) {
        [self stopTimer];
        timeOld=60;
        [self.codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.codeButton setTitle:@"获取验证码" forState:UIControlStateSelected];
        self.codeButton.userInteractionEnabled = YES;
        
    }
}
- (void)stopTimer{
    
    if (_timer == nil) {
        return;
    }
    [_timer invalidate];
    _timer = nil;
}

- (void)dealloc{
    
   NSLog(@"%s",__func__);
    [_timer invalidate];
    _timer = nil;
}
- (void)btnCancleAction:(UIButton *)btn{
    if ([CJStringWithFormat(@"%@",self.dicData[@"needSmsCode"]) isEqualToString:@"yes"]) {
        if ([self.phoneTextField.text isEqualToString:@""]) {
            [CJAlert showStringDismissWithDelay:@"请选择手机号"];
            return;
        }
        if ([CJRegular getIsStrEmpty:self.codeTextField.text]) {
            [CJAlert showStringDismissWithDelay:@"请输入验证码"];
            return;
        }
    }
    if (self.payType.length == 0) {
        [CJAlert showStringDismissWithDelay:@"请选择打款商户"];
        return;
    }
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail/batchPayment",CJBaseUrl);

    NSMutableDictionary *dicPar = [NSMutableDictionary dictionary];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"advancePaymentAmount"]) forKey:@"advancePaymentAmount"];
    [dicPar setValue:self.dicData[@"orderDetailCodeList"] forKey:@"orderDetailCodeList"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"allSumAmount"]) forKey:@"allSumAmount"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"currentPaymentAmount"]) forKey:@"currentPaymentAmount"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"driverAmount"]) forKey:@"driverAmount"];
    [dicPar setValue:self.dicData[@"message"] forKey:@"message"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"needSmsCode"]) forKey:@"needSmsCode"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"oilTotalAmount"]) forKey:@"oilTotalAmount"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"payStep"]) forKey:@"payStep"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"payType"]) forKey:@"payType"];
    [dicPar setValue:payeeType forKey:@"payeeType"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"paymentAmount"]) forKey:@"paymentAmount"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"totalReceiptPayAmount"]) forKey:@"totalReceiptPayAmount"];
    [dicPar setValue:CJStringWithFormat(@"%@",self.dicData[@"currentPaymentAmount"]) forKey:@"amount"];
    [dicPar setValue:self.phoneStr forKey:@"phone"];
    [dicPar setValue:self.codeTextField.text forKey:@"smsCode"];
    [dicPar setValue:self.payType forKey:@"payPlatform"];
   
    
    WS(ws);
    NSData *jsonDagta = [NSJSONSerialization dataWithJSONObject:dicPar options:(NSJSONWritingPrettyPrinted) error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonDagta encoding:(NSUTF8StringEncoding)];
    NSDictionary *dict = @{@"dataStr": jsonString};
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dict status:OperationTip success:^(id  _Nonnull responseObject) {
        [ws pop];
        } failure:^(NSError * _Nonnull error) {
            
        }];
   
}
@end
